import Vue from 'vue'
import Router from 'vue-router'
import Layout from '@/layout'
import store from '@/store'
import { getUnitInfo } from '@/config.js'

const originalPush = Router.prototype.push

Router.prototype.push = function push(location) {
  return originalPush.call(this, location).catch(err => err)
}

Vue.use(Router)

// 访客身份：底部tab配置
export const visitorTabs = [
  {
    path: 'visitorSend',
    name: '访客预约',
    imgSurname: 'visitorSend',
    meta: { keepAlive: true },
    component: () => import('@/views/visitor/visitorSend')
  },
  {
    path: 'visitorRecord',
    name: '拜访记录',
    imgSurname: 'visitorRecord',
    component: () => import('@/views/visitor/visitorRecord')
  },
  {
    path: 'visitorInfo',
    name: '个人信息',
    imgSurname: 'visitorInfo',
    component: () => import('@/views/visitor/visitorInfo')
  }
]

// 访客权限页面
export const visitorAuthPath = [
  {
    path: '/visitor',
    component: Layout,
    redirect: '/visitor/visitorSend',
    children: [...visitorTabs]
  },
  {
    path: '/visitorSuccess',
    component: () => import('@/views/visitor/visitorSuccess')
  },
  {
    path: '/visitorHelp',
    component: () => import('@/views/visitor/visitorHelp')
  }
]

// 管理员权限页面
export const adminAuthPath = [
  {
    path: '/adminOrderList',
    component: () => import('@/views/admin/orderList')
  },
  {
    path: '/adminOrderDetail',
    component: () => import('@/views/admin/orderDetail')
  }
]

const router = new Router({
  routes: [
    {
      path: '/',
      component: () => import('@/views/login/index.vue')
    },
    {
      path: '/publicAuth',
      component: () => import('@/views/login/publicAuth')
    },
    {
      path: '/phoneAuth',
      component: () => import('@/views/login/phoneAuth')
    },
    ...visitorAuthPath,
    ...adminAuthPath,
    {
      path: '/404',
      component: () => import('@/views/404/index')
    },
    {
      path: '*',
      redirect: '/404'
    }
  ]
})

router.beforeEach(async(to, from, next) => {
  const hasToken = localStorage.getItem('visitorH5_token')
  if (!hasToken) {
    if (to.path === '/' || to.path === '/publicAuth') {
      next()
    } else {
      // 其他页面
      if (store.getters.isPublic) {
        window.location.href = getUnitInfo().publicUrl
      } else {
        window.location.href = getUnitInfo().H5Url
      }
    }
  } else {
    next()
  }
})

export default router
